package com.ywjt.pinkelephant.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import com.ywjt.pinkelephant.R;
import com.ywjt.pinkelephant.util.SPUtils;

public class WindowsManagerPicker implements View.OnClickListener {
    @SuppressLint("StaticFieldLeak")
    private static Context mContext;
    private View mRecoveryView;
    private WindowManager.LayoutParams mRecoveryParams;
    private static final int RECOVERY_Y = 1500;
    private static final int RECOVERY_X = 750;
    private boolean canVibratio = true;
    private Activity mActivity;
    private static final int UP_MESSAGE_WHAT = 100;
    private static final int DOWN_MESSAGE_WHAT = 200;

    private RoundRelativeLayout rlContainer;
    private  ImageView ivClose;
    private ImageView ivRefresh;
    private ImageView ivPlay;
    private ImageView ivRevolve;
    private ImageView ivLarge;
    private TextView tvText;
    private NestedScrollView scrollView;
    private TextView tvBackStart;
    private final Handler mHandler = new Handler();


    public static void init(@NonNull Context context) {
        mContext = context;
    }

    private static WindowsManagerPicker mPicker;

    private WindowsManagerPicker(Activity activity) {
        this.mActivity = activity;
    }

    public static WindowsManagerPicker newInstances(Activity activity) {
        synchronized (WindowsManagerPicker.class) {
            if (mPicker == null) {
                synchronized (WindowsManagerPicker.class) {
                    mPicker = new WindowsManagerPicker(activity);
                }
            }
        }
        return mPicker;
    }

    /**
     * 创建悬浮球
     */
    @SuppressLint("ClickableViewAccessibility")
    public void createFloatingWindows() {

        if (rlContainer == null) {
            final WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
            if (windowManager == null)
                return;
            rlContainer = (RoundRelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.popu_suspended, null);
            rlContainer.setRadius(17);
            final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            layoutParams.format = PixelFormat.RGBA_8888;
            layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE |//低版本默认的type类型
                        WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;//设置该窗口的type类型为顶层
            }
            layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
            layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
            layoutParams.x = 0;
            layoutParams.y = 0;
            windowManager.addView(rlContainer, layoutParams);
             ivClose=rlContainer.findViewById(R.id.ivClose);
             ivRefresh=rlContainer.findViewById(R.id.ivRefresh);
            tvText=rlContainer.findViewById(R.id.tvText);
            ivRevolve=rlContainer.findViewById(R.id.ivRevolve);
            ivLarge=rlContainer.findViewById(R.id.ivLarge);
            ivPlay=rlContainer.findViewById(R.id.ivPlay);
            scrollView=rlContainer.findViewById(R.id.scrollView);
            tvBackStart=rlContainer.findViewById(R.id.tvBackStart);

            if (SPUtils.getSharedIntData(mContext,"PopuTextColor")!=0){
                tvText.setTextColor(SPUtils.getSharedIntData(mContext,"PopuTextColor"));
            }

            if (SPUtils.getSharedIntData(mContext,"PopuBgColor")!=0){
                rlContainer.setBackgroundColor(SPUtils.getSharedIntData(mContext,"PopuBgColor"));
            }

            if (SPUtils.getSharedIntData(mContext,"PopuTextSize")!=0){
                tvText.setTextSize(SPUtils.getSharedIntData(mContext,"PopuTextSize"));
            }

            if (SPUtils.getSharedFloatData(mContext,"PopuTextTransparent")!=0){
                rlContainer.setAlpha((100-SPUtils.getSharedFloatData(mContext,"PopuTextTransparent"))/100);
            }

             ivClose.setOnClickListener(this::onClick);
            tvText.setOnClickListener(this::onClick);
             ivRefresh.setOnClickListener(this::onClick);
            ivPlay.setOnClickListener(this::onClick);
            ivRevolve.setOnClickListener(this::onClick);
            tvBackStart.setOnClickListener(this::onClick);
            ivLarge.setOnClickListener(this::onClick);
            rlContainer.setOnTouchListener(new View.OnTouchListener() {
                int x, y = 0;

                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            x = (int) event.getRawX();
                            y = (int) event.getRawY();
                            break;
                        case MotionEvent.ACTION_MOVE:
                            int nowX = (int) event.getRawX();
                            int nowY = (int) event.getRawY();
                            int movedX = nowX - x;
                            int movedY = nowY - y;
                            x = nowX;
                            y = nowY;
                            layoutParams.x = layoutParams.x + movedX;
                            layoutParams.y = layoutParams.y + movedY;

                            if (mRecoveryView != null) {
                                if (nowY >= RECOVERY_Y && nowX >= RECOVERY_X) {
                                    mRecoveryParams.x = 450;
                                    mRecoveryParams.y = 850;
                                    windowManager.updateViewLayout(mRecoveryView, mRecoveryParams);
                                    if (canVibratio) {
                                        vibratePhone();
                                        canVibratio = false;
                                    }
                                } else {
                                    mRecoveryParams.x = 500;
                                    mRecoveryParams.y = 900;
                                    windowManager.updateViewLayout(mRecoveryView, mRecoveryParams);
                                    canVibratio = true;
                                }
                            }

                            if (rlContainer != null) {
                                windowManager.updateViewLayout(rlContainer, layoutParams);
                            }

                            break;
                        case MotionEvent.ACTION_UP:
                            int nowUpX = (int) event.getRawX();
                            int nowUpY = (int) event.getRawY();
//                            if (nowUpY >= RECOVERY_Y && nowUpX >= RECOVERY_X) {
//                                removeFloatingView();
//                            }
                            break;
                        default:
                            break;
                    }
                    return false;
                }
            });

            mHandler.post(ScrollRunnable);
        }
    }


    private void removeFloatingView() {
        final WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        if (windowManager == null)
            return;
        if (rlContainer != null) {
            windowManager.removeView(rlContainer);
            rlContainer = null;
        }
    }

    /**
     * 振动功能
     */
    private void vibratePhone() {
        Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
        if (vibrator != null && vibrator.hasVibrator()) {
            vibrator.vibrate(100);
        }
    }

    public void onDestroy() {
        removeFloatingView();
        mPicker = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivClose:
                removeFloatingView();
                break;
            case R.id.ivRefresh:
                //刷新
                break;
            case R.id.ivPlay:
                //开始
                mHandler.post(ScrollRunnable);
                ivPlay.setVisibility(View.GONE);
                break;
            case R.id.tvBackStart:
                scrollView.fullScroll(ScrollView.FOCUS_UP);
                mHandler.post(ScrollRunnable);
                break;
            case R.id.tvText:
                mHandler.removeCallbacks(ScrollRunnable);
                 ivPlay.setVisibility(View.VISIBLE);
                break;
            case R.id.ivRevolve:
                //旋转
                rlContainer.setRotation(90);
                break;
        }
    }

    /**
     * 滚屏的线程
     */
    private Runnable ScrollRunnable = new Runnable() {
        @SuppressLint("NewApi")
        @Override
        public void run() {
            int off = tvText.getMeasuredHeight() - scrollView.getHeight();// 判断高度
            if (off > 0) {
                scrollView.scrollBy(0, SPUtils.getSharedIntData(mContext,"PopuTextSpeed")/10);
                if (scrollView.getScaleY() == off) {
                    Thread.currentThread().interrupt();
                } else {
                    mHandler.postDelayed(this, 100);
                }
            }
        }
    };
}